﻿# -*- coding: utf-8 -*-
import sys  
reload(sys)
sys.setdefaultencoding('utf8')  
import string
import cgi
import urllib

from sgmllib import SGMLParser, SGMLParseError
from google.appengine.api import urlfetch
from google.appengine.ext import webapp
from google.appengine.ext.webapp.util import run_wsgi_app

appmainurl = u"http://mapps.renren.com"
loginurl = u"http://3g.renren.com/login.do?fx=0&autoLogin=true"
proxyurl = u""
form_fields = {
#	"uid": u"",
#	"url": u"",
	"origURL": u"/home.do",
	"email": u"",
	"password": u"",
	"login": u""
}

form_fields_get = {
	"uid": u"",
	"url": u"",
}

retrymax = 20

class PageHTMLParser(SGMLParser):
	def __init__(self):
		SGMLParser.__init__(self)
		self.links = []
		self.datasets = []
		self.matchcheck = 0
		self.eigentag = ''
		self.eigenname = ''
		self.eigendata = ''
		self.dupcounter = 0

	def handle_data(self, text):
		txt = text.strip()
		if txt.find(self.eigendata) != -1:
			self.matchcheck = 1
			self.datasets.append(txt)

	def start_a(self, attr):
		self.links += [v for k, v in attr if k == "href"]

	def end_a(self):
		if self.matchcheck == 1:
			self.matchcheck = 0
		else:
			self.links.pop()
			self.dupcounter += 1

class HTMLInputParser(SGMLParser):
	def __init__(self):
		SGMLParser.__init__(self)
		self.linksnames = []
		self.linksvalues = []
		self.pairs = 0
	def start_input(self, attr):
		self.linksnames += [v for k, v in attr if k == 'name']
		self.linksvalues += [v for k, v in attr if k == 'value']
		self.pairs += 1

useremail = u''
userpasswords = u''
useruid = u'1'

class SetAcount(webapp.RequestHandler):
	def ReapPlants(self, loginuser, passwords, helper = ''):
#		self.response.out.write(u'<html><meta http-equiv="content-type" content="text/html; charset=UTF-8"><body><pre>你输入的用户名是：<br />')
#		self.response.out.write(loginuser.decode('utf-8'))
#		self.response.out.write(u'<br />你输入的密码是：<br />')
#		self.response.out.write(passwords.decode('utf-8'))
#		self.response.out.write(u'<br />')
#		self.response.out.write(u'</pre>')
#		form_fields['uid'] = useruid.encode('utf-8')
#		form_fields['url'] = loginurl.encode('utf-8')
		form_fields['login'] = u'登录'
		form_fields['password'] = passwords
		form_fields['email'] = loginuser
		form_data = urllib.urlencode(form_fields)
		result = urlfetch.fetch(url=loginurl, payload=form_data, method=urlfetch.POST, headers={'Content-Type': 'application/x-www-form-urlencoded','User-Agent':'Mozilla/5.0 (SymbianOS/9.4; Series60/5.0 Nokia5800 XpressMusic-1/50.0.5; Profile/MIDP-2.1 Configuration/CLDC-1.1; en-us) AppleWebKit/525 (KHTML, like Gecko) WicKed/7.1.123'}, allow_truncated=True)
		success = 0
		retrycounter = 0
		while (success == 0 or success == 1) and retrycounter < retrymax and result.content.find('帐号和密码不匹配') != -1:
			try:
				retrycounter += 1
				result = urlfetch.fetch(url=loginurl, payload=form_data, method=urlfetch.POST, headers={'Content-Type': 'application/x-www-form-urlencoded'}, allow_truncated=True, deadline=30)
			except:
				success = 1
			if success == 0:
				success = 2
			else:
				success = 0
		if success != 2:
			self.response.out.write(success)
#			return
#		self.response.out.write(result.content.decode('utf-8'))
		hp = PageHTMLParser()
		hp.eigentag = 'a'
		hp.eigenname = 'href'
		hp.eigendata = '应用'
		hp.feed(result.content)
		hp.close
#		self.response.out.write(hp.links)
#		inurl = proxyurl + 'uid=' + useruid + '&url=' + hp.links[0];
		success = 0
		retrycounter = 0
		while (success == 0 or success == 1) and retrycounter < retrymax:
			try:
				retrycounter += 1
				result = urlfetch.fetch(url=hp.links[0], payload=[], method=urlfetch.GET, allow_truncated=True, deadline=30)
			except:
				success = 1
			if success == 0:
				success = 2
			else:
				success = 0
		if success != 2:
			self.response.out.write(success)
#			return
#		self.response.out.write(result.content.decode('utf-8'))
		hp = PageHTMLParser()
		hp.eigentag = 'a'
		hp.eigenname = 'href'
		hp.eigendata = '人人农场'
		hp.feed(result.content)
		hp.close
#		form_fields_get['url'] = hp.links[0].encode('utf-8')
#		form_data = urllib.urlencode(form_fields_get)
		success = 0
		retrycounter = 0
		while (success == 0 or success == 1) and retrycounter < retrymax:
			try:
				retrycounter += 1
				result = urlfetch.fetch(url=hp.links[0], payload=[], method=urlfetch.GET, allow_truncated=True, deadline=30)
			except:
				success = 1
			if success == 0:
				success = 2
			else:
				success = 0
		if success != 2:
			self.response.out.write(success)
#			return
#		self.response.out.write(result.content.decode('utf-8'))
		if result.content.find('第三方应用\"人人农场\"发生错误') != -1:
			self.response.out.write(result.content.decode('utf-8'))
			return
		cropurl = appmainurl + result.content[result.content.find('/rr_farm/farm/action/wap,myCropAction'):result.content.find('\">【农田】')]
		treeurl = appmainurl + result.content[result.content.find('/rr_farm/farm/action/wap,myTreeAction'):result.content.find('\">【果树】')]
		animalurl = appmainurl + result.content[result.content.find('/rr_farm/farm/action/wap,myAnimalAction'):result.content.find('\">【畜牧】')]
		machineurl = appmainurl + result.content[result.content.find('/rr_farm/farm/action/wap,myMachineAction'):result.content.find('\">【机械】')]
		friendurl = appmainurl + result.content[result.content.find('/rr_farm/farm/action/wap,myFriendsListAction'):result.content.find('\">【好友农场】')]
		if result.content.find('【农田】★') != -1:
			resultcrop = urlfetch.fetch(url=proxyurl + cropurl, payload=[], method=urlfetch.GET, allow_truncated=True, deadline=30)
			if resultcrop.content.find('收获全部农产品') != -1:
				reapallcropurl = appmainurl + resultcrop.content[resultcrop.content.find('/rr_farm/farm/action/wap,reapAllAction'):resultcrop.content.find('\">收获全部农产品')]
				urlfetch.fetch(url=proxyurl + reapallcropurl, payload=[], method=urlfetch.GET, allow_truncated=True, deadline=30)
#				self.response.out.write(result.content.decode('utf-8'))
		if result.content.find('【果树】★') != -1:
			resulttree = urlfetch.fetch(url=proxyurl + treeurl, payload=[], method=urlfetch.GET, allow_truncated=True, deadline=30)
			if resulttree.content.find('收获全部果树产品') != -1:
				reapalltreeurl = appmainurl + resulttree.content[resulttree.content.find('/rr_farm/farm/action/wap,reapAllAction'):resulttree.content.find('\">收获全部果树产品')]
				urlfetch.fetch(url=proxyurl + reapalltreeurl, payload=[], method=urlfetch.GET, allow_truncated=True, deadline=30)
#				self.response.out.write(result.content.decode('utf-8'))
		if result.content.find('【畜牧】★') != -1:
			resultanimal = urlfetch.fetch(url=proxyurl + animalurl, payload=[], method=urlfetch.GET, allow_truncated=True, deadline=30)
			resultanimal2 = urlfetch.fetch(url=proxyurl + animalurl + "&curpage=1", payload=[], method=urlfetch.GET, allow_truncated=True, deadline=30)
			if resultanimal.content.find('收获全部畜牧产品') != -1:
				reapallanimalurl = appmainurl + resultanimal.content[resultanimal.content.find('/rr_farm/farm/action/wap,reapAllAction'):resultanimal.content.find('\">收获全部畜牧产品')]
				reapallresult = urlfetch.fetch(url=proxyurl + reapallanimalurl, payload=[], method=urlfetch.GET, allow_truncated=True, deadline=30)
#				self.response.out.write(reapallresult.content.decode('utf-8'))
			if helper == '':
				if resultanimal.content.find('喂食') != -1:
					animalresultstr = resultanimal.content[resultanimal.content.find('/rr_farm/farm/action/wap,feedAction'):]
					feedurls = []
#						self.response.out.write(helperanimalresultstr)
					while animalresultstr.find('喂食') != -1:
						feedurls.append(appmainurl + animalresultstr[animalresultstr.find('/rr_farm/farm/action/wap,feedAction'):animalresultstr.find('\" class=\"blue\">喂食')])
						animalresultstr = animalresultstr[animalresultstr.find('喂食'):]
						animalresultstr = animalresultstr[animalresultstr.find('食'):]
					for j in range(0, len(feedurls)):
						feedurl = feedurls[j]
						feedpage = urlfetch.fetch(url=feedurl, payload=[], method=urlfetch.GET, allow_truncated=True, deadline=30)
						feedposturl = appmainurl + feedpage.content[feedpage.content.find('/rr_farm/farm/action/wap,feedAction'):feedpage.content.find('\"><input type=\"hidden\" name=\"sid\"')]
						leftstr = feedpage.content[feedpage.content.find('【仓库剩余】&nbsp;'):]
						leftstr = leftstr[leftstr.find(';') + 1:leftstr.find('<br/>')]
						left = int(leftstr)
#						self.response.out.write(leftstr)
						hp = HTMLInputParser()
						hp.feed(feedpage.content)
						hp.close
						feedform = {}
						for i in range(0, hp.pairs):
							feedform[hp.linksnames[i]] = hp.linksvalues[i].encode('utf-8')
						feednum = int(feedform['pc'])
#						self.response.out.write(feednum)
						if left < feednum:
							continue
						if feedform.has_key('submit1'):
							pass
						else:
							feedform['submit1'] = u'确 定'.encode('utf-8')
						feedform_data = urllib.urlencode(feedform)
						self.response.out.write(feedform)
						self.response.out.write('<br />')
						self.response.out.write(feedposturl)
						self.response.out.write('<br />')
						self.response.out.write('<br />')
						self.response.out.write(hp.linksnames)
						self.response.out.write('<br />')
						self.response.out.write(hp.linksvalues)
						feedresult = urlfetch.fetch(url=feedposturl, payload=feedform_data, method=urlfetch.POST, headers={'Content-Type': 'application/x-www-form-urlencoded'}, allow_truncated=True, deadline=30)
						self.response.out.write(feedresult.content)
				if resultanimal2.content.find('喂食') != -1:
					animalresultstr = resultanimal2.content[resultanimal.content.find('/rr_farm/farm/action/wap,feedAction'):]
					feedurls = []
#						self.response.out.write(helperanimalresultstr)
					while animalresultstr.find('喂食') != -1:
						feedurls.append(appmainurl + animalresultstr[animalresultstr.find('/rr_farm/farm/action/wap,feedAction'):animalresultstr.find('\" class=\"blue\">喂食')])
						animalresultstr = animalresultstr[animalresultstr.find('喂食'):]
						animalresultstr = animalresultstr[animalresultstr.find('食'):]
					for j in range(0, len(feedurls)):
						feedurl = feedurls[j]
						feedpage = urlfetch.fetch(url=feedurl, payload=[], method=urlfetch.GET, allow_truncated=True, deadline=30)
						feedposturl = appmainurl + feedpage.content[feedpage.content.find('/rr_farm/farm/action/wap,feedAction'):feedpage.content.find('\"><input type=\"hidden\" name=\"sid\"')]
						leftstr = feedpage.content[feedpage.content.find('【仓库剩余】&nbsp;'):]
						leftstr = leftstr[leftstr.find(';') + 1:leftstr.find('<br/>')]
						left = int(leftstr)
#						self.response.out.write(leftstr)
						hp = HTMLInputParser()
						hp.feed(feedpage.content)
						hp.close
						feedform = {}
						for i in range(0, hp.pairs):
							feedform[hp.linksnames[i]] = hp.linksvalues[i].encode('utf-8')
						feednum = int(feedform['pc'])
#						self.response.out.write(feednum)
						if left < feednum:
							continue
						if feedform.has_key('submit1'):
							pass
						else:
							feedform['submit1'] = u'确 定'.encode('utf-8')
						feedform_data = urllib.urlencode(feedform)
						self.response.out.write(feedform)
						self.response.out.write('<br />')
						self.response.out.write(feedposturl)
						self.response.out.write('<br />')
						self.response.out.write('<br />')
						self.response.out.write(hp.linksnames)
						self.response.out.write('<br />')
						self.response.out.write(hp.linksvalues)
						feedresult = urlfetch.fetch(url=feedposturl, payload=feedform_data, method=urlfetch.POST, headers={'Content-Type': 'application/x-www-form-urlencoded'}, allow_truncated=True, deadline=30)
						self.response.out.write(feedresult.content)
		if result.content.find('【机械】★') != -1:
			resultmachine = urlfetch.fetch(url=proxyurl + machineurl, payload=[], method=urlfetch.GET, allow_truncated=True, deadline=30)
			resultmachine2 = urlfetch.fetch(url=proxyurl + machineurl + "&curpage=1", payload=[], method=urlfetch.GET, allow_truncated=True, deadline=30)
			if resultmachine.content.find('收获全部加工产品') != -1:
				reapallmachineurl = appmainurl + resultmachine.content[resultmachine.content.find('/rr_farm/farm/action/wap,reapAllAction'):resultmachine.content.find('\">收获全部加工产品')]
				reapallresult = urlfetch.fetch(url=proxyurl + reapallmachineurl, payload=[], method=urlfetch.GET, allow_truncated=True, deadline=30)
#				self.response.out.write(reapallresult.content.decode('utf-8'))
			if helper == '':
				if resultmachine.content.find('添加') != -1:
					machineresultstr = resultmachine.content[resultmachine.content.find('/rr_farm/farm/action/wap,feedAction'):]
					feedurls = []
					while machineresultstr.find('添加') != -1:
						if machineresultstr.find('\" class=\"blue\">添加') != -1:
							urltmp = appmainurl + machineresultstr[machineresultstr.find('/rr_farm/farm/action/wap,feedAction'):machineresultstr.find('\" class=\"blue\">添加')]
						else:
							urltmp = appmainurl + machineresultstr[machineresultstr.find('/rr_farm/farm/action/wap,feedAction'):machineresultstr.find('\">添加')]
						feedurls.append(urltmp)
						machineresultstr = machineresultstr[machineresultstr.find('添加'):]
						machineresultstr = machineresultstr[machineresultstr.find('加'):]
#					self.response.out.write(feedurls)
					for j in range(0, len(feedurls)):
						feedurl = feedurls[j]
						feedpage = urlfetch.fetch(url=feedurl, payload=[], method=urlfetch.GET, allow_truncated=True, deadline=30)
						feedposturl = appmainurl + feedpage.content[feedpage.content.find('/rr_farm/farm/action/wap,feedAction'):feedpage.content.find('\"><input type=\"hidden\" name=\"sid\"')]
						leftstr = feedpage.content[feedpage.content.find('【仓库剩余】&nbsp;'):]
						leftstr = leftstr[leftstr.find(';') + 1:leftstr.find('<br/>')]
#						self.response.out.write(feedpage.content)
#						self.response.out.write('<br />')
#						self.response.out.write('leftstr')
						left = int(leftstr)
						hp = HTMLInputParser()
						hp.feed(feedpage.content)
						hp.close
						feedform = {}
						for i in range(0, hp.pairs):
							feedform[hp.linksnames[i]] = hp.linksvalues[i].encode('utf-8')
						feednum = int(feedform['pc'])
#						self.response.out.write(feednum)
						if left < feednum:
							continue
						if feedform.has_key('submit1'):
							pass
						else:
							feedform['submit1'] = u'确 定'.encode('utf-8')
						feedform_data = urllib.urlencode(feedform)
						feedresult = urlfetch.fetch(url=feedposturl, payload=feedform_data, method=urlfetch.POST, headers={'Content-Type': 'application/x-www-form-urlencoded'}, allow_truncated=True, deadline=30)
						self.response.out.write(feedresult.content)
				if resultmachine2.content.find('添加') != -1:
					machineresultstr = resultmachine2.content[resultmachine.content.find('/rr_farm/farm/action/wap,feedAction'):]
					feedurls = []
					while machineresultstr.find('添加') != -1:
						if machineresultstr.find('\" class=\"blue\">添加') != -1:
							urltmp = appmainurl + machineresultstr[machineresultstr.find('/rr_farm/farm/action/wap,feedAction'):machineresultstr.find('\" class=\"blue\">添加')]
						else:
							urltmp = appmainurl + machineresultstr[machineresultstr.find('/rr_farm/farm/action/wap,feedAction'):machineresultstr.find('\">添加')]
						feedurls.append(urltmp)
						machineresultstr = machineresultstr[machineresultstr.find('添加'):]
						machineresultstr = machineresultstr[machineresultstr.find('加'):]
#					self.response.out.write(feedurls)
					for j in range(0, len(feedurls)):
						feedurl = feedurls[j]
						feedpage = urlfetch.fetch(url=feedurl, payload=[], method=urlfetch.GET, allow_truncated=True, deadline=30)
						feedposturl = appmainurl + feedpage.content[feedpage.content.find('/rr_farm/farm/action/wap,feedAction'):feedpage.content.find('\"><input type=\"hidden\" name=\"sid\"')]
						leftstr = feedpage.content[feedpage.content.find('【仓库剩余】&nbsp;'):]
						leftstr = leftstr[leftstr.find(';') + 1:leftstr.find('<br/>')]
#						self.response.out.write(feedpage.content)
#						self.response.out.write('<br />')
#						self.response.out.write('leftstr')
						left = int(leftstr)
						hp = HTMLInputParser()
						hp.feed(feedpage.content)
						hp.close
						feedform = {}
						for i in range(0, hp.pairs):
							feedform[hp.linksnames[i]] = hp.linksvalues[i].encode('utf-8')
						feednum = int(feedform['pc'])
#						self.response.out.write(feednum)
						if left < feednum:
							continue
						if feedform.has_key('submit1'):
							pass
						else:
							feedform['submit1'] = u'确 定'.encode('utf-8')
						feedform_data = urllib.urlencode(feedform)
						feedresult = urlfetch.fetch(url=feedposturl, payload=feedform_data, method=urlfetch.POST, headers={'Content-Type': 'application/x-www-form-urlencoded'}, allow_truncated=True, deadline=30)
						self.response.out.write(feedresult.content)
						
	def get(self):
		if cgi.escape(self.request.get('email')) != "":
			useremail = cgi.escape(self.request.get('email'))
			useremail = useremail.decode("utf-8")
		else:
			return
		if cgi.escape(self.request.get('pwd')) != "":
			userpasswords = cgi.escape(self.request.get('pwd'))
			userpasswords = userpasswords.decode("utf-8")
		else:
			return
		self.ReapPlants(useremail, userpasswords)
#		useremail = u'flamepjlh@126.com'
#		userpasswords = u'flamehjhj'
#		self.ReapPlants(useremail, userpasswords)
#		useremail = u'flamepjlh@163.com'
#		userpasswords = u'flamehjhj'
#		self.ReapPlants(useremail, userpasswords)

application = webapp.WSGIApplication(
																		 [('/feedself', SetAcount)],
																		 debug=True)

def main():
	run_wsgi_app(application)

if __name__ == "__main__":
	main()